package com.xiaohe.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xiaohe.common.constant.ProductConstant;
import com.xiaohe.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.xiaohe.gulimall.product.dao.AttrGroupDao;
import com.xiaohe.gulimall.product.dao.CategoryDao;
import com.xiaohe.gulimall.product.entity.*;
import com.xiaohe.gulimall.product.service.AttrAttrgroupRelationService;
import com.xiaohe.gulimall.product.service.CategoryService;
import com.xiaohe.gulimall.product.vo.AttrGroupRelationVo;
import com.xiaohe.gulimall.product.vo.AttrRespVo;
import com.xiaohe.gulimall.product.vo.AttrVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaohe.common.utils.PageUtils;
import com.xiaohe.common.utils.Query;

import com.xiaohe.gulimall.product.dao.AttrDao;
import com.xiaohe.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
@Slf4j
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }



    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        //1.保存基本数据
        this.save(attrEntity);
        //2.保存关联关系的表
        if(attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId()!=null){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            //属性分组的id
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            //属性id
            relationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(relationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId,String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(attrType)?1:0);
        if (catelogId !=0){
            queryWrapper.eq("catelog_id",catelogId);
        }
        //检索条件
         String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper)->{
                wrapper.eq("attr_id",key)
                        .or()
                        .like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
               queryWrapper
        );
         PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();

        List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //设置分类和分组的名字
            if("base".equalsIgnoreCase(attrType)){
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if(relationEntity!=null){
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    if (attrGroupEntity != null && attrGroupEntity.getAttrGroupId()!=null) {
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Transactional
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo respVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity,respVo);
        //"attrGroupId": 1, //分组id
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //设置分组信息
            QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("attr_id",attrId);
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(wrapper);
            if(relationEntity!=null){
                respVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity!=null){
                    respVo.setAttrName(attrGroupEntity.getAttrGroupName());
                }
        }
        }
        //"catelogPath": [2, 34, 225] //分类完整路径
        //设置分类信息
        if(attrEntity!=null){
            Long catelogId = attrEntity.getCatelogId();
            Long[] catelogPath = categoryService.findCatelogPath(catelogId);
            respVo.setCatelogPath(catelogPath);
        }
        return respVo;
    }

    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //修改关联表
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());
            UpdateWrapper<AttrAttrgroupRelationEntity> wrapper = new UpdateWrapper<>();
            wrapper.eq("attr_id", attr.getAttrId());
            QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("attr_id", attr.getAttrId());
            Integer count = attrAttrgroupRelationDao.selectCount(queryWrapper);
            //大于0为修改操作
            if (count > 0) {
                attrAttrgroupRelationDao.update(relationEntity, wrapper);
            } else {
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }
    }

    //根据分组id关联所有的属性
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_group_id",attrgroupId);
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(wrapper);
        List<Long> attrIds = entities.stream().map((item) -> {
            Long attrId = item.getAttrId();
            return attrId;
        }).collect(Collectors.toList());
        if(attrIds == null || attrIds.size() ==0){
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void removeRelation(AttrGroupRelationVo[] vos) {
        List<AttrGroupRelationVo> attrGroupRelationVos = Arrays.asList(vos);
        List<AttrAttrgroupRelationEntity> collect = attrGroupRelationVos.stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelation(collect);
    }

    //获取没有关联的分组信息
    @Override
    public PageUtils getNoRelation(Map<String, Object> params, String attrgroupId) {
        //当前分组只能关联自己所属分类的属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        //获取分类id
        Long catelogId = attrGroupEntity.getCatelogId();
        //当前分类下的其他分组
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));


        List<Long> collect =  attrGroupEntities.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
            //这些分组关联的属性
            List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));

            List<Long> attrIds = entities.stream().map((item) -> {
                return item.getAttrId();
            }).collect(Collectors.toList());
            //从当前分类的所有属性中移除这些属性
            QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
            QueryWrapper<AttrEntity> entityQueryWrapper = queryWrapper.eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
            if(attrIds !=null && attrIds.size()>0){
                entityQueryWrapper.notIn("attr_id", attrIds);
            }
            String key = (String) params.get("key");
            if(StringUtils.isNotEmpty(key)){
                entityQueryWrapper.and((w)->{
                    w.eq("attr_id",key).or()
                            .like("attr_name",key);
                });
            }
            IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), entityQueryWrapper);
            PageUtils pageUtils = new PageUtils(page);
            return pageUtils;
    }

    //在指定所有属性集合里面挑出检索属性
    @Override
    public List<Long> selectSearchAttrsIds(List<Long> attrIds) {

        return this.baseMapper.selectSearchAttrsIds(attrIds);
    }


}